<template>
    <div>
        <el-row type="flex" justify="end" class="header toolbar">
            <el-col :span="2" class="header-btn">
                <el-button type="primary" @click="addAuthGroup">添加</el-button>
            </el-col>
        </el-row>
        <!-- 表格开始  -->
        <el-table
                stripe
                ref="multipleTable"
                :data="authList"
                tooltip-effect="dark"
                style="width: 100%">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    label="名称">
                <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>
            <el-table-column
                    prop="status"
                    label="状态">
                <template slot-scope="scope">{{ scope.row.status ? '启用': '禁用' }}</template>
            </el-table-column>
            <el-table-column
                    prop="create_time"
                    label="添加时间">
            </el-table-column>
            <el-table-column
                    label="操作">
                <template slot-scope="scope">
                    <el-button type="info" size="mini" @click="editAuthGroup(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="mini" @click="delAuthGroup(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 页码 -->
        <el-col :span="24" class="toolbar">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="pageSizes"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-col>

        <!--   添加角色的dialog     -->
        <el-dialog
                title="添加角色"
                :visible.sync="addDialogVisible"
                width="50%"
                @close="addClose">
            <el-form :model="addRuleForm" :rules="rules" ref="addRuleForm" label-width="100px">
                <el-form-item label="权限组名称" prop="name">
                    <el-input v-model="addRuleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="是否禁用">
                    <el-select v-model="addRuleForm.status" placeholder="请选择">
                        <el-option
                                v-for="item in status"
                                :key="item.key"
                                :label="item.key"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="分配权限" required>
                    <el-tree
                            :data="rulesList"
                            show-checkbox
                            node-key="id"
                            ref="tree"
                            :props="defaultProps">
                    </el-tree>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="addClose">取 消</el-button>
                <el-button type="primary" @click="addSure">确 定</el-button>
            </span>
        </el-dialog>

        <!--   编辑角色的dialog     -->
        <el-dialog
                title="编辑角色"
                :visible.sync="editDialogVisible"
                width="50%"
                @close="editClose">
            <el-form :model="editRuleForm" :rules="rules" ref="editRuleForm" label-width="100px">
                <el-form-item label="权限组名称" prop="name">
                    <el-input v-model="editRuleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="是否禁用">
                    <el-select v-model="editRuleForm.status" placeholder="请选择">
                        <el-option
                                v-for="item in status"
                                :key="item.key"
                                :label="item.key"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="分配权限" required>
                    <el-tree
                            :data="rulesList"
                            show-checkbox
                            node-key="id"
                            ref="treeEdit"
                            :default-checked-keys="editRuleForm.rules"
                            :props="defaultProps">
                    </el-tree>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="editClose">取 消</el-button>
                <el-button type="primary" @click="editSure">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {addAuthGroup, authGroupList, getNode, editAuthGroup, delAuthGroup, findAuthgroup} from '../../api/userAPI'

    export default {
        name: "Role",
        data() {
            return {
                tableData: [],
                // status: '',
                // keyword: '',
                authList: [],
                total: 0,
                pageSize: 10, // 每页显示条目个数
                pageSizes: [10, 20, 30, 40], // 每页显示个数选择器的选项设置
                currentPage: 1, // 当前页数
                addDialogVisible: false,
                addRuleForm: {
                    name: '',
                    rules: [],
                    status: ''
                },
                rules: {
                    name: [
                        { required: true, message: '请输入权限组名称', trigger: 'blur' },
                    ]
                },
                status: [
                    {
                        key: '启用',
                        value: 1
                    },
                    {
                        key: '禁用',
                        value: 0
                    }
                ],
                rulesList: [],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                editDialogVisible: false,
                editRuleForm: {},
                editRuleFormCopy: {},
                editId: ''
            }
        },
        created() {
            this._authGroupList() // 获取后台权限组列表
        },
        methods: {
            _authGroupList() {
                let data = {p: this.currentPage, length: this.pageSize}
                authGroupList(data).then(res => {
                    console.log(res)
                    this.authList = res.data.list
                    this.total = res.data.total
                }).catch(err => {
                    this.$message.error(err.response.data.message)
                })
            },
            editAuthGroup(index, row) {
              console.log(row)
              this.editId = row.id
              this.rulesList = []
              this._getNode()
              this.editDialogVisible = true
            },
            delAuthGroup(index, row) {
                console.log(row)
                this.$confirm('确认删除该角色吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    let data = {ids: [row.id],delete: 1}
                    delAuthGroup(data).then(res => {
                        this.$message.success('删除成功')
                        this._authGroupList() // 获取后台权限组列表
                    }).catch(err => {
                        this.$message.error(err.response.data.message)
                    })
                }).catch(() => {
                    this.$message.info('已取消')
                })
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`)
                // 改变每页显示的条数
                this.pageSize = val
                this._authGroupList() // 获取后台权限组列表
                // 注意：在改变每页显示的条数时，要将页码显示到第一页
                this.currentPage = 1
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`)
                this.currentPage = val
                this._authGroupList() // 获取后台权限组列表
            },
            addAuthGroup() {
                this.addDialogVisible = true
                this._getNode()
            },
            _getNode() {
                getNode().then(res => {
                  console.log(res)
                  this.rulesList = res.data
                  findAuthgroup({id: this.editId}).then(res => {
                    console.log(res)
                    this.editRuleForm = res.data.list
                    this.editRuleFormCopy = {...this.editRuleForm}
                    if (!Array.isArray(this.editRuleForm.rules)) {
                      let arr = this.editRuleForm.rules.split(',')
                      this.editRuleForm.rules = arr.map((val) => val - 0)
                    }
                    // console.log(this.editRuleForm)
                  }).catch(err => {
                    this.$message.error(err.response.data.message)
                  })
                }).catch(err => {
                    this.$message.error(err.response.data.message)
                })
            },
            addClose() {
                this.addDialogVisible = false
                this.$refs.addRuleForm.resetFields()
            },
            addSure() {
                // console.log(this.$refs.tree.getCheckedNodes(false, true)) // 通过 node 获取,包含半节点
                // console.log(this.$refs.tree.getCheckedKeys()) // 通过 node 获取
                if (this.addRuleForm.status === '') {
                    delete this.addRuleForm.status
                }
                this.addRuleForm.rules = this.$refs.tree.getCheckedKeys()
                // this.addRuleForm.rules = this.$refs.tree.getCheckedNodes(false, true)
                // this.addRuleForm.rules = this.addRuleForm.rules.map(item => item.id)
                this.$refs.addRuleForm.validate( (valid) => {
                    if (!valid) return false
                    if (this.addRuleForm.rules.length <= 0) return this.$message.warning('请选择分配权限')
                    // console.log(this.addRuleForm)
                    addAuthGroup(this.addRuleForm).then(res => {
                        this.$message.success('添加成功')
                        this.addDialogVisible = false
                        this._authGroupList() // 获取后台权限组列表
                    }).catch(err => {
                        this.$message.error(err.response.data.message)
                    })
                })
            },
            editClose() {
                this.editDialogVisible = false
                this.$refs.editRuleForm.resetFields()
                this.editRuleForm = {}
                // this.editRuleForm.name = this.editRuleFormCopy.name
                // this.editRuleForm.status = this.editRuleFormCopy.status
                // if (!Array.isArray(this.editRuleFormCopy.rules)) {
                //     let arr = this.editRuleFormCopy.rules.split(',')
                //     this.editRuleFormCopy.rules = arr.map((val) => val - 0)
                //     this.editRuleForm.rules = this.editRuleFormCopy.rules
                // }
            },
            editSure() {
                this.editRuleForm.rules = this.$refs.treeEdit.getCheckedKeys()
                // let rules = this.$refs.treeEdit.getCheckedNodes(false,true)
                let data = {
                  id: this.editRuleForm.id,
                  name: this.editRuleForm.name,
                  rules: this.editRuleForm.rules,
                  status: this.editRuleForm.status
                }
                // console.log(data)
                editAuthGroup(data).then(res => {
                    this.$message.success('修改成功')
                    this.editDialogVisible = false
                    this._authGroupList() // 获取后台权限组列表
                }).catch(err => {
                    this.$message.error(err.response.data.message)
                })
            }
        }
    }
</script>

<style scoped lang="scss">
    .header {
        /*margin-top: 10px;*/
    }
    .el-input,.el-select {
        width: 80%;
    }
</style>
